#ifndef _CROSSENGINE_RECYCLEID_H_
#define _CROSSENGINE_RECYCLEID_H_

namespace Cross
{

template<class T>
class RecycleId
{
public:
  RecycleId(T minId, T maxId);
  ~RecycleId();
  bool Get(T& id);
  void Put(T id);
private:
  struct Node
  {
    T id;
    Node* next;
  };
  Node* _mem;
  Node* _head;
  T _minId;
  T _maxId;
};

template<class T>
RecycleId<T>::RecycleId(T minId,T maxId)
{
  _minId=minId;
  _maxId=maxId;
  T size=maxId-minId+1;
  assert(size>0);
  T temp=minId;
  _mem=new Node[size];
  _head=_mem;
  for(T i=0;i<size-1;++i)
  {
    _mem[i].id=temp++;
    _mem[i].next=&_mem[i+1];
  }
  assert(temp==minId+size-1);
  _mem[size-1].id=temp++;
  _mem[size-1].next=nullptr;
}

template<class T>
RecycleId<T>::~RecycleId()
{
  delete[] _mem;
}

template<class T>
bool RecycleId<T>::Get(T& id)
{
    if(_head)
    {
        id=_head->id;
        _head=_head->next;
        return true;
    }
    return false;
}

template<class T>
void RecycleId<T>::Put(T id)
{
  assert(id>=_minId&&id<=_maxId);
  if(id>=_minId&&id<=_maxId)
  {
      Node* node=&_mem[id-_minId];
      node->next=_head;
      _head=node;
  }
}

}
#endif//_CROSSENGINE_RECYCLEID_H_
